// frenchCompare.js

// 移除标点符号
function removePunctuation(text) {
    return text.replace(/[^\w\s]/g, '');
}

// 计算相似度得分
export function calculateScore(referenceText, userText) {
    // 先检查两个文本是否完全相同
    if (removePunctuation(referenceText.trim().toLowerCase()) === removePunctuation(userText.trim().toLowerCase())) {
        return 100;
    }

    const referenceWords = referenceText.trim().toLowerCase().split(/\s+/);
    const userWords = userText.trim().toLowerCase().split(/\s+/);

    // 移除标点符号
    const cleanReferenceWords = referenceWords.map(removePunctuation);
    const cleanUserWords = userWords.map(removePunctuation);

    // 计算词汇匹配度
    let correctWords = 0;
    const minLength = Math.min(cleanReferenceWords.length, cleanUserWords.length);

    for (let i = 0; i < minLength; i++) {
        if (cleanReferenceWords[i] === cleanUserWords[i]) {
            correctWords++;
        }
    }

    // 计算基本得分
    const basicScore = Math.round((correctWords / cleanReferenceWords.length) * 100);

    // 添加一些额外的评分因素（词序、语法等）
    // 在实际应用中，这里可以接入更复杂的NLP分析
    let additionalFactors = 0;

    // 词序相似度
    const wordOrderSimilarity = calculateWordOrderSimilarity(cleanReferenceWords, cleanUserWords);
    additionalFactors += wordOrderSimilarity * 10;

    // 最终得分
    let finalScore = Math.min(100, Math.max(0, basicScore + additionalFactors));

    return finalScore;
}

// 计算词序相似度
function calculateWordOrderSimilarity(reference, user) {
    if (reference.length === 0 || user.length === 0) return 0;

    const matchedPositions = [];

    for (let i = 0; i < user.length; i++) {
        const indexInReference = reference.indexOf(user[i]);
        if (indexInReference !== -1) {
            matchedPositions.push({ userPos: i, refPos: indexInReference });
        }
    }

    if (matchedPositions.length === 0) return 0;

    // 计算词序相似度
    let orderScore = 0;
    for (const match of matchedPositions) {
        const positionDiff = Math.abs(match.userPos - match.refPos);
        orderScore += Math.max(0, 1 - (positionDiff / reference.length));
    }

    return orderScore / matchedPositions.length;
}